package spotGUI.ElementViewer;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import managers.DBManager;
import managers.messengerManager.SpotFeedbackManager;
import managers.socialNetworkManagers.ElementsManager;
import managers.socialNetworkManagers.SocialNetworkManager;
import spotGUI.utils.UserListCellRenderer;
import utils.StackTracePrinter;

import com.toedter.calendar.JDateChooser;

import elements.Comment;
import elements.Element;
import elements.Vote;
import java.util.ResourceBundle;

public class ElementViewer extends JPanel {

	private static final int DEFAULT_QUANTITY = 15;

	private JPanel filter;
	private JButton btnFiltra;
	private JComboBox quantityBox;
	private JDateChooser dateChooserFrom;
	private JDateChooser dateChooserTo;
	private JLabel lbl2;
	private JLabel lbl3;
	private JLabel lbl5;
	private JComboBox typeBox;
	private JLabel lbl4;
	private JScrollPane scrollPane;
	private JLabel lblWarning;

	private int userId;
	private JPanel panel;

	private ElementPanel elementPanel;


	/**
	 * @wbp.parser.constructor
	 */
	public ElementViewer (ElementPanel elementPanel) {
		this(ElementsManager.ALL_USERS, elementPanel);
	}

	public ElementViewer(int userId, ElementPanel elementPanel) {

		this.elementPanel  = elementPanel;
		this.userId = userId;

		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{328, 0};
		gridBagLayout.rowHeights = new int[]{68, 377, 0};
		gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);

		filter = new JPanel();
		filter.setPreferredSize(new Dimension(340, 50));
		filter.setMaximumSize(new Dimension(340, 50));
		filter.setMinimumSize(new Dimension(340, 50));
		GridBagConstraints gbc_filter = new GridBagConstraints();
		gbc_filter.fill = GridBagConstraints.VERTICAL;
		gbc_filter.anchor = GridBagConstraints.EAST;
		gbc_filter.insets = new Insets(0, 0, 5, 0);
		gbc_filter.gridx = 0;
		gbc_filter.gridy = 0;
		add(filter, gbc_filter);
		FlowLayout fl_filter = new FlowLayout(FlowLayout.LEFT, 4, 5);
		filter.setLayout(fl_filter);

		lbl2 = new JLabel(ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.lbl2.text")); //$NON-NLS-1$ //$NON-NLS-2$
		filter.add(lbl2);

		dateChooserFrom = new JDateChooser();
		dateChooserFrom.setPreferredSize(new Dimension(112, 21));
		filter.add(dateChooserFrom);

		lbl3 = new JLabel(ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.lbl3.text")); //$NON-NLS-1$ //$NON-NLS-2$
		filter.add(lbl3);

		dateChooserTo = new JDateChooser();
		dateChooserTo.setPreferredSize(new Dimension(112, 21));
		dateChooserTo.setOpaque(false);
		filter.add(dateChooserTo);

		lbl4 = new JLabel(ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.lbl4.text")); //$NON-NLS-1$ //$NON-NLS-2$
		filter.add(lbl4);

		Object[] o0= {ElementsManager.ALL_TYPES, ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.5")};
		Object[] o1= {Element.POST, ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.2")};
		Object[] o2= {Element.PHOTO, ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.3")};
		Object[] o3= {Element.PERSONAL_MESSAGE, ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.4")};
		Object[] o = {o0, o1, o2, o3};

		typeBox = new JComboBox();
		typeBox.setPreferredSize(new Dimension(100, 22));
		typeBox.setRenderer(new UserListCellRenderer());	
		typeBox.setModel(new DefaultComboBoxModel(o));
		filter.add(typeBox);

		lbl5 = new JLabel(ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.lbl5.text")); //$NON-NLS-1$ //$NON-NLS-2$
		filter.add(lbl5);

		quantityBox = new JComboBox();
		quantityBox.setModel(new DefaultComboBoxModel(new String[] {"10", "15", "25", "40"}));
		filter.add(quantityBox);

		btnFiltra = new JButton(ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.btnFiltra.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnFiltra.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					filter();
				} catch (IllegalArgumentException e) {
					lblWarning.setVisible(true);
					StackTracePrinter.print(e);
				}

			}
		});
		filter.add(btnFiltra);

		lblWarning = new JLabel(""); //$NON-NLS-1$ //$NON-NLS-2$
		lblWarning.setIcon(new ImageIcon(ElementViewer.class.getResource("/images/Icons/24x24px/warning.png")));
		lblWarning.setVisible(false);
		filter.add(lblWarning);

		scrollPane = new JScrollPane();
		scrollPane.setOpaque(false);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 1;
		add(scrollPane, gbc_scrollPane);


		panel = new JPanel();
		scrollPane.setViewportView(panel);
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		
	}

	private void filter () {
		Date fromDate = dateChooserFrom.getDate();
		Date toDate = dateChooserTo.getDate();
		Timestamp from;
		Timestamp to;

		if (fromDate == null) {
			from = ElementsManager.ALWAYS;
		} else
			from = new Timestamp(fromDate.getTime());
		if (toDate == null) {
			to = ElementsManager.ALWAYS;
		} else
			to = new Timestamp(toDate.getTime());

		if (fromDate != null && toDate != null) {
			if (fromDate.compareTo(toDate) > 0) {
				throw new IllegalArgumentException("FROM date is greater than TO date.");
			}
		}
		
		lblWarning.setVisible(false);
		setElements(from, to, (Integer)(((Object[])typeBox.getSelectedItem())[0]), userId,
				Integer.parseInt((String)quantityBox.getSelectedItem()));
	}


	private void setElements(final Timestamp from, final Timestamp to, final int type, final int userId, final int quantity) {
		new Thread() {
			@Override
			public void run() {
				panel.removeAll();
				validate();
				repaint();
				try {
					ArrayList<Element> a = ElementsManager.retrieveElements(DBManager.getConnection(), from, to, userId, type, quantity);
					for (int i = 0; i < a.size(); i++) {
						Element element = a.get(i);
						ArrayList<Comment> comments = ElementsManager.retrieveComments(DBManager.getConnection(), element.elementId);
						ArrayList<Vote> votes = ElementsManager.retrieveVotes(DBManager.getConnection(), element.elementId);

						panel.add(createElementView(element, comments, votes));
						validate();
					}
				} catch (SQLException e) {
					SocialNetworkManager.getSharedInstance().getFeedbackManager().updateStatus(
							ResourceBundle.getBundle("spotGUI.ElementViewer.messages").getString("ElementViewer.1"),SpotFeedbackManager.WARNING);
					StackTracePrinter.print(e);
				}
			}
		}.start();

	}


	private JPanel createElementView(Element element, ArrayList<Comment> comments, ArrayList<Vote> votes) {

		JPanel view = new ElementView(element, elementPanel);

		view = new MarkableDecoratorView(view, votes);
		view = new CommentableViewDecorator(view, comments);

		return view;
	}


	public void clearAndUpdate() {
		setElements(ElementsManager.ALWAYS, ElementsManager.ALWAYS, ElementsManager.ALL_TYPES, userId, DEFAULT_QUANTITY);
	}
}

